﻿Imports Ionic.Zip

Partial Class WebForm_ManageVBook_UploadPhoto
    Inherits System.Web.UI.UserControl

    Protected Sub btnBatchUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBatchUpload.Click
        If Me.BatchUpload() = True Then
            MyObj.ShowMessage("上傳成功")
        End If
    End Sub

    Protected Sub btnBatchUpload_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBatchUpload.PreRender
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(sender)
    End Sub

End Class

#Region "BLL"
Partial Class WebForm_ManageVBook_UploadPhoto
    Private ReadOnly Property photoBasePath() As String
        Get
            If ViewState("photoBasePath") Is Nothing Then
                ViewState("photoBasePath") = MyObj.GetFilePath("VBookPhoto")
            End If

            Return ViewState("photoBasePath")
        End Get
    End Property

    Protected Sub UpdateVolunteerPhoto(ByVal volunteerID As String, ByVal ext As String)
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("update Volunteer set ")
        sql.AppendFormat("PhotoPath = '{0}{1}' ", volunteerID, ext)
        sql.AppendFormat("where VolunteerID = '{0}' ", volunteerID)

        dat.AccData(sql)

    End Sub

    Private Function BatchUpload() As Boolean
        Dim fileName As String = Me.fuUploadFileName.FileName

        Try
            Using zip As ZipFile = ZipFile.Read(Me.fuUploadFileName.PostedFile.InputStream)
                Dim e As ZipEntry

                Using scope As New Transactions.TransactionScope
                    For Each e In zip
                        'MyObj.WriteLog(photoBasePath)
                        e.Extract(Server.MapPath(Me.photoBasePath), ExtractExistingFileAction.OverwriteSilently)

                        Dim volunteerID As String = IO.Path.GetFileNameWithoutExtension(e.FileName.Substring(0, 10).ToString())
                        Dim ext As String = IO.Path.GetExtension(e.FileName)

                        Me.UpdateVolunteerPhoto(volunteerID, ext)
                    Next

                    scope.Complete()
                End Using
            End Using

            MyObj.ShowMessage("Success")
        Catch ex1 As Exception
            MyObj.WriteLog(ex1.Message)

            MyObj.ShowMessage("Upload failed")
            Return False
        End Try

        Return True
    End Function
End Class

#End Region
